const utils = {
  REG: {
    /**
     * 正则验证(可扩展)
     * @param  {String} str  需要检测的字符串
     * @param  {String} type 检测类型
     * @return {Boolean}     返回布尔值
     */
    testReg (str, type) {
      switch (type) {
        case 'email':
          return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str)
        case 'phone':
          return /^1[3|4|5|7|8][0-9]{9}$/.test(str)
        case 'tel':
          return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str)
        case 'number':
          return /^[0-9]$/.test(str)
        case 'english':
          return /^[a-zA-Z]+$/.test(str)
        case 'chinese':
          return /^[\u4E00-\u9FA5]+$/.test(str)
        case 'lower':
          return /^[a-z]+$/.test(str)
        case 'upper':
          return /^[A-Z]+$/.test(str)
        case 'bank':
          return /^([1-9]{1})(\d{15}|\d{18})$/.test(str)
        default:
          return true
      }
    },
    /**
     * 检测密码强度
     * checkPwdLv('12asdASAD') -> 3
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    checkPwdLv (str) {
      let nowLv = 0

      // 密码长度 < 6，强度为 0
      if (str.length < 6) {
        return nowLv
      }
      // 密码长度 >= 6，全为数字，强度加 1
      if (/[0-9]/.test(str)) {
        nowLv++
      }
      // 密码长度 >= 6，全为小写字母，强度加 1
      if (/[a-z]/.test(str)) {
        nowLv++
      }
      // 密码长度 >= 6，全为大写字母，强度加 1
      if (/[A-Z]/.test(str)) {
        nowLv++
      }

      return nowLv
    },
    clearNoNum (obj) {
      obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符   
      obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的   
      obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3'); //只能输入4个小数   
      if (obj.value.indexOf(".") < 0 && obj.value != "") { //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
        obj.value = parseFloat(obj.value);
      }
    },
    subPhone (str) {
      return str.replace(/^(\d{3})\d+(\d{4})$/, "$1****$2");
    },
    subAddress (str, frontLen, endLen) {
      var len = str.length - frontLen - endLen
      var xing = ''
      for (var i = 0; i < len; i++) {
        xing += '*'
        if (xing.length > 4) {
          xing = "****"
        }
      }
      return str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
    },
    // 百分比转换小数
    toPoint (percent) {
      if (!percent) {
        return false
      }
      var str = percent.replace("%", "");
      str = str / 100;
      return str;
    },
    // 小数转化为百分数
    toPercent (point) {
      if (!point) {
        return false
      }
      var str = Number(point * 100).toFixed(1);
      str += "%";
      return str;
    },
    // 进度条
    toProgess (point) {
      if (!point) {
        return false
      }
      var str = Number(point * 100).toFixed(1)
      return str;
    },
  },
  DOM: {
    // 函数节流
    debounce (fn, delay) {
      let timer = null
      return function (...args) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    },
    //ios 兼容，input失去焦点后界面上移不恢复的问题
    resetInput () {
      setTimeout(() => {
        let scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
        window.scrollTo(0, Math.max(scrollHeight - 1, 0));
      }, 100)
    },
    // 浏览器后退不刷新,该场景主要出现在 webview 后退的时候
    loadBrowser () {
      window.onpageshow = (evt) => {
        if (evt.persisted) {
          document.body.style.display = "none";
          location.reload();
        }
      }
    },
    /**
   * 动态创建 <script>
   */
    createScript (url, charset = 'utf-8') {
      let script = document.createElement('script')
      script.setAttribute('type', 'text/javascript')
      script.setAttribute('charset', charset)
      script.setAttribute('src', url)
      script.async = true

      return script
    },
  },
  STR: {
    /**
       * 去掉前后空格
       * 1:前后空格(默认)  2:所有空格  3:前空格 4:后空格
       * @param  {[type]} str  [description]
       * @param  {Number} type [description]
       * @return {[type]}      [description]
       */
    trim (str, type = 1) {
      switch (type) {
        case 1:
          return str.replace(/(^\s*)|(\s*$)/g, '')
        case 2:
          return str.replace(/\s+/g, '')
        case 3:
          return str.replace(/(^\s*)/g, '')
        case 4:
          return str.replace(/(\s*$)/g, '')
        default:
          return str
      }
    },
    /**
     * 大小写转换
     * 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写
     */
    changeCase (str, type) {
      function ToggleCase (str) {
        var itemText = ''
        str.split('').forEach(
          function (item) {
            if (/^([a-z]+)/.test(item)) {
              itemText += item.toUpperCase()
            } else if (/^([A-Z]+)/.test(item)) {
              itemText += item.toLowerCase()
            } else {
              itemText += item
            }
          })
        return itemText
      }
      switch (type) {
        case 1:
          return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
            return v1.toUpperCase() + v2.toLowerCase()
          })
        case 2:
          return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
            return v1.toLowerCase() + v2.toUpperCase()
          })
        case 3:
          return ToggleCase(str)
        case 4:
          return str.toUpperCase()
        case 5:
          return str.toLowerCase()
        default:
          return str
      }
    },

    /**
     * 如何优雅的实现金钱格式化
     * 1234567890 --> 1,234,567,890
     * @return {[type]}       [description]
     */
    formatMoney (str = '1234567890') {
      return str.replace(/\B(?=(\d{3})+(?!\d))/g, ',') // 1,234,567,890

      // return str.split('').reverse().reduce((prev, next, index) => {
      // return ((index % 3) ? next : (next + ',')) + prev
      // })
    },
    addPreZero (num) {
      var t = (num + '').length,
        s = '';
      for (var i = 0; i < 64 - t; i++) {
        s += '0';
      }
      return s + num;
    }
  },
  TIME: {
    // 转换时间戳
    timestampToTime (date) {
      if (date == null || date === "") {
        return "";
      }
      var date = new Date(date * 1000);
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10 ?
          "0" + (date.getMonth() + 1) :
          date.getMonth() + 1) + "-";
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    /**
     * 获取当前时间
     * 2017-08-11 22:52:13 星期六
     * @param  {Boolean} hasDay  是否需要年月日
     * @param  {Boolean} hasHour 是否需要十分秒
     * @param  {Boolean} hasWeek 是否需要星期
     * @param  {String} sign1 分隔符
     * @param  {String} sign2 分隔符
     */
    getNowDate (hasDay = true, hasHour = true, hasWeek = true, sign1 = '-', sign2 = ':') {
      let date = new Date()
      let year = date.getFullYear()
      let month = (date.getMonth() + 1).toString().padStart(2, '0')
      let day = (date.getDate()).toString().padStart(2, '0')
      let hour = (date.getHours()).toString().padStart(2, '0')
      let minutes = (date.getMinutes()).toString().padStart(2, '0')
      let seconds = (date.getSeconds()).toString().padStart(2, '0')
      let weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
      let week = weekArr[date.getDay()]

      let time1 = hasDay ? `${year}${sign1}${month}${sign1}${day}` : ''
      let time2 = hasHour ? `${hour}${sign2}${minutes}${sign2}${seconds}` : ''
      let time3 = hasWeek ? `${week}` : ''

      return `${time1} ${time2} ${time3}`.replace(/(^\s*)|(\s*$)/g, '')
    },

    /**
     * 格式化时间戳 (分:秒)
     * 61 -> 01:01
     * @param  {Number} timestamp 时间戳
     * @param  {String} sign      分隔符，默认 :
     * @return {[type]}           [description]
     */
    format (timestamp, sign = ':') {
      timestamp = Math.floor(timestamp)

      let minute = (Math.floor(timestamp / 60)).toString().padStart(2, '0')
      let second = (timestamp % 60).toString().padStart(2, '0')
      return `${minute}${sign}${second}`
    },

    /**
     * 倒计时
     * countDown('2017-8-11 24:0:0') -> 剩余0天0小时54分钟41秒
     * @param  {Date} endTime 结束时间
     * @return {[type]}         [description]
     */
    countDown (endTime) {
      let start = new Date()
      let end = new Date(endTime)
      let dif = end.getTime() - start.getTime()

      let d = 0
      let h = 0
      let m = 0
      let s = 0

      if (dif >= 0) {
        d = Math.floor(dif / 1000 / 3600 / 24)
        h = Math.floor(dif / 1000 / 60 / 60 % 24)
        m = Math.floor(dif / 1000 / 60 % 60)
        s = Math.floor(dif / 1000 % 60)
      }

      return `仅剩${d}天${h}小时${m}分钟${s}秒`
    }
  },
  WEB: {
    navigators () {
      var current = 'unknow';
      var u = navigator.userAgent
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isAndroid) {
        return current = "android";
      } else if (isIOS) {
        return current = "ios";
      } else {
        return current;
      }
    }
  },
  UNICODE: {
    // unicode 解码
    decodeUnicode (str) {
      return unescape(str.replace(/\\u/gi, '%u'))
    },
    // 转译 unicode
    encodeUnicode (str) {
      let res = [];
      for (let i = 0; i < str.length; i++) {
        res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
      }
      return "\\u" + res.join("\\u");
    },
  }
}

export default utils